package no.ntnu.item.ttm4120.dhcp;

import java.util.ArrayList;
import java.util.Iterator;

import no.ntnu.item.ttm4120.dhcp.data.AddressPoolEntity;

public class LeaseHandler implements Runnable{

	private static long sleep = 10000;
	private AddressServer server = null;
	
	public LeaseHandler(AddressServer server) {
		this.server = server;
	}
	//1267197019646
	//1267197019647
	@Override
	public synchronized void run() {
		while(true){
			try {
				Thread.sleep(sleep);
				
				ArrayList<AddressPoolEntity> list = new ArrayList<AddressPoolEntity>(server.getAddressPool().getPool().values());
				for (AddressPoolEntity addressPoolEntity : list) {
					if (addressPoolEntity.getLeaseTimeEnd() < System.currentTimeMillis() && 
							addressPoolEntity.isAssigned() && 
							addressPoolEntity.getServer() == server.getServerPos()){
//						System.out.println("Current Time: " + System.currentTimeMillis());
						System.out.println("Lease expired for: " + addressPoolEntity);
						server.leaseExpired(addressPoolEntity);
					}
				}
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
		}
	}

}